package com.jumi.microservice.rocketmq.listener;

import com.alibaba.fastjson.JSONObject;
import com.jumi.microservice.common.exception.GlobalExceptionHandler;
import com.jumi.microservice.domain.Account;
import com.jumi.microservice.domain.Log;
import com.jumi.microservice.domain.temp.DepartmentTemp;
import com.jumi.microservice.mapper.AccountMapper;
import com.jumi.microservice.mapper.DepartmentMapper;
import com.jumi.microservice.mapper.LogMapper;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * - - - - - - - - - - - - - - -
 *
 * @author liuz
 * @date 2020/7/25 10:07
 * ToDoSomeThing
 * - - - - - - - - - - - - - - -
 */
@Component
public class Mqlistener  implements MessageListenerConcurrently {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    private LogMapper logMapper;

    private DepartmentMapper departmentMapper;

    private AccountMapper accountMapper;

    public Mqlistener(LogMapper logMapper, DepartmentMapper departmentMapper, AccountMapper accountMapper){
        this.logMapper = logMapper;
        this.departmentMapper = departmentMapper;
        this.accountMapper = accountMapper;
    }

    public LogMapper getLogMapper() {
        return logMapper;
    }

    public void setLogMapper(LogMapper logMapper) {
        this.logMapper = logMapper;
    }

    public DepartmentMapper getDepartmentMapper() {
        return departmentMapper;
    }

    public void setDepartmentMapper(DepartmentMapper departmentMapper) {
        this.departmentMapper = departmentMapper;
    }

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        // msgs中只收集同一个topic，同一个tag，并且key相同的message
        // 会把不同的消息分别放置到不同的队列中
        try {
            for (Message msg : list) {
                log.info("Consumer-获取消息={}",msg);
                String body = new String(msg.getBody(), "utf-8");
                log.info("Consumer-获取消息-主题topic为={}, 消费消息为={}", msg.getTopic(), body);
                if(StringUtils.isNotEmpty(body)){
                    Log log = JSONObject.toJavaObject(JSONObject.parseObject(body), Log.class);
                    saveLog(log);
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    /**
     * 保存log日志
     * @param log
     */
    private void saveLog(Log log){
        //先获取用户信息
        Account ac = accountMapper.selectById(log.getAccountId());
        if(ac!=null) {
            log.setUserName(ac.getUserName());
            log.setDepartmentId(ac.getDepartmentId());
            log.setMobile(ac.getMobile());
            log.setDepartmentName(getDepName(ac.getDepartmentId()));
        }
        logMapper.insert(log);
    }

    /**
     * 获取无限上级部门名称
     * @param depid 当前部门id
     * @return
     */
    private String getDepName(Long depid){
       StringBuilder sb = new StringBuilder();
       //获取无线上级部门
       List<DepartmentTemp> list = departmentMapper.selectParentDep(depid);
       list.stream().forEach(d->{
           sb.append(d.getDepartmentName());
           //不为最后低级部门继续添加 ->
           if(list.indexOf(d)!=list.size()-1) {
               sb.append("->");
           }
       });
        return sb.toString();
    }
}
